package com.test.thread.demo1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Printabc3 {
    Lock lock = new ReentrantLock();
    Condition cA = lock.newCondition();
    Condition cB = lock.newCondition();
    Condition cC = lock.newCondition();

    private String curLetter = "A";

    public void setLetter(){
        if ("A".equals(curLetter)){
            this.curLetter = "B";
        }else if ("B".equals(curLetter)){
            this.curLetter = "C";
        }else {
            this.curLetter = "A";
        }
    }

    public void printA(String letter){
        print(letter, cA, cB);
    }

    public void printB(String letter){
        print(letter, cB, cC);
    }

    public void printC(String letter){
        print(letter, cC, cA);
    }

    private void print(String letter, Condition cur, Condition next) {
        for (int i = 0; i < 10; i++){
            try {
                lock.lock();
                if (!curLetter.equals(letter)){
                    cur.await();
                }

                System.out.print(letter);
                setLetter();
                next.signal();

            }catch (Exception e){

            }finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        Printabc3 printabc3 = new Printabc3();

        new Thread(() -> {
            printabc3.printA("A");
        }, "A").start();

        new Thread(() -> {
            printabc3.printB("B");
        }, "B").start();

        new Thread(() -> {
            printabc3.printC("C");
        }, "C").start();
    }
}